from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, HTMLBody, FileAttachment
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
import urllib3

# 忽略requests证书警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 此句用来消除ssl证书错误，exchange使用自签证书需加上
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter


def Email(subject, body, attachmentspath=None):
    creds = Credentials(
        username='helpdesk',  # 账号
        password='**********'  # 密码
    )
    account = Account(
        primary_smtp_address='helpdesk@abcd.com.cn',  # 发送方邮箱地址
        credentials=creds,
        autodiscover=True,
        access_type=DELEGATE
    )
    m = Message(
        account=account,
        subject=subject,
        body=HTMLBody(body),
        to_recipients=[Mailbox(email_address="zhangsan@abcd.com.cn"), Mailbox(email_address="lisi@abcd.com.cn")]
    )

    # # 添加附件
    # attachments = []
    # with open(r"{}/巡检报告.pdf".format(attachmentspath), 'rb') as f:
    #     content = f.read()
    # attachments.append(('巡检报告.pdf', content))
    #
    # # 附加文件
    # for attachment_name, attachment_content in attachments or []:
    #     file = FileAttachment(name=attachment_name, content=attachment_content)
    #     m.attach(file)

    m.send_and_save()


if __name__ == '__main__':
    body = '网络设备自动巡检报告，脚本发送请勿回复。'

    # "接收方的邮箱", "邮件标题", "邮件内容", "报告路径"
    Email("网络设备巡检", body=body, attachmentspath=r'F:\PythonProgram\交换机巡检\LOG\2022-06-25_09-38-04')
